package com.gxc.webcore.util;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class SystemUtil {

	private static Map<String, String> cache = new HashMap<String, String>();

	public static String get(String key) {
		if (!StringUtil.isTrimEmpty(key)) {
			return cache.get(key.trim().toLowerCase());
		}
		return null;
	}

	public static void set(String key, String value) {
		if (!StringUtil.isTrimEmpty(key)) {
			cache.put(key.trim().toLowerCase(), value);
		}
	}

	public static void remove(String key) {
		if (!StringUtil.isTrimEmpty(key)) {
			cache.remove(key.trim().toLowerCase());
		}
	}

	public static void clear() {
		cache.clear();
	}

	@SuppressWarnings("unchecked")
	public static void init() {
		String filePath = ContextUtil.getApplicationRealPath()
				+ "/WEB-INF/config/system.xml";
		Document doc = null;
		try {
			SAXReader reader = new SAXReader();
			doc = reader.read(new File(filePath));
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (doc != null) {
			List<Node> nodeList = doc.selectNodes("//system/property");
			String key = null;
			String value = null;
			for (Node node : nodeList) {
				key = node.selectSingleNode("key").getText().trim();
				value = node.selectSingleNode("value").getText().trim();
				SystemUtil.set(key, value);
			}
		}
	}

}
